package com.huluobo.a2202mvvm_im_douyindemo.login;

import androidx.lifecycle.MutableLiveData;

import com.huluobo.a2202mvvm_im_douyindemo.bean.LoginBeanResult;
import com.huluobo.a2202mvvm_im_douyindemo.mvvmBase.BaseRepo;
import com.hyphenate.EMCallBack;

import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.RequestBody;

/**
 * Created by LC on 2024/4/19.
 */
public class LoginRepo extends BaseRepo {
    public void loginEase(String username, String password, MutableLiveData<LoginUserBean> success,
                          MutableLiveData<String> failed) {
        emClient.login(username, password, new EMCallBack() {
            @Override
            public void onSuccess() {
                //主线程赋值
//                success.setValue(new LoginUserBean(username, password));
                //一般回调中,都处于子线程,所以不能用LiveData的主线程赋值
                //子线程赋值
                success.postValue(new LoginUserBean(username, password));
            }

            @Override
            public void onError(int code, String error) {
//                failed.setValue(error);
                failed.postValue(error);
            }
        });
    }

    public void login(RequestBody body, MutableLiveData<LoginBeanResult> success, MutableLiveData<String> failed) {
        apiService.login(body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginBeanResult>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(LoginBeanResult loginBeanResult) {
                        success.setValue(loginBeanResult);
                    }

                    @Override
                    public void onError(Throwable e) {
                        failed.setValue(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
